//
//  WDMyNotifyController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/30.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDMyNotifyController.h"
#import "WDMyNotifyCell.h"
#import "WDMyNotify.h"
#import "WDLoan.h"
#import "WDProductDynamicController.h"
#import "WDBusinessDetailController.h"
#import "WDCheckController.h"
#import "WDPlaceholderView.h"

@interface WDMyNotifyController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation WDMyNotifyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WDBackColor;
    
    if ([self respondsToSelector:@selector(clickNavLeft)]) {
        
    [self loadNavItemWithAction:@selector(clickNavLeft) btnImage:@"actionbar" btnSelImage:@"actionbar" title:@"我的通知"];
    }
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self setUpTalbleView];
    
    self.placeView = [self loadPlaceViewWithImageName:@"icon_loading" status:@"努力加载中..."];
    
    [self sendRequest];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)sendRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"current_page" : @1,
                                 @"limit" : @10,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotify];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self hideLoadView];
        
        [self.dataArray removeAllObjects];
        
        [self.dataArray addObjectsFromArray:[WDMyNotify mj_objectArrayWithKeyValuesArray:responseObject[@"data"]]];
        
        if (!self.dataArray.count) {
            
            [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"目前暂无通知"];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"网络连接异常"];
        
    }];
}

#pragma mark - 记载控件
- (void)setUpTalbleView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = WDBackColor;
    [self.view addSubview:tableView];
    
    self.tableView = tableView;
    
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(0);
    }];
    
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
        
        NSDictionary *parameters = @{
                                     @"current_page":@(self.page),
                                     @"limit":@10,
                                     @"ctype":@3
                                     };
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotify];
        
        [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDMyNotify class]) parameters:parameters succeed:^(id responseObject) {
            
            if (!self.dataArray.count) {
                
                [self showPlaceViewWithImageName:@"icon_loadFailed" status:@"目前暂无通知"];
            }
            
        } filed:nil];
    }];
    
    tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        
        NSDictionary *parameters = @{
                                     @"current_page":@(self.page),
                                     @"limit":@10,
                                     @"ctype":@3
                                     };
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLGetNotify];
        
        [self sendRequestDataWithURLStr:url Model:NSStringFromClass([WDMyNotify class]) parameters:parameters succeed:nil filed:nil];
    }];
}

#pragma mark - 消息查看回调
- (void)sendCallBackWithMsgID:(NSString *)msgID
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"msg_id":msgID,
                                 @"ctype":@3
                                 };
    
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLMessageCallBack];
    
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //WDLog(@"%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@", error);
        
    }];
}
	
#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDMyNotifyCell *cell = [WDMyNotifyCell myNotifyCellWithTableView:tableView];
    
    WDMyNotify *myNotify = self.dataArray[indexPath.row];
    
    cell.myNotify = myNotify;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDMyNotify *myNotify = self.dataArray[indexPath.row];
    return myNotify.myNotifyCellH;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    WDMyNotify *notify = self.dataArray[indexPath.row];
    
    //消除红点和改变文字颜色
    notify.status = @"1";
    WDMyNotifyCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.myNotify = notify;
    
    [self sendCallBackWithMsgID:notify.msg_id];
    
    //跳转查看具体通知（根据push_type跳转不同的页面）
    switch ([notify.push_type intValue]) {
            
        case WDPushTypeLoanDetail://贷款详情
        {
            //[self sendRequestWithFinanceID:notify.finance_id];
            
            WDCheckController *tempVC = [[WDCheckController alloc] init];
            tempVC.financeID = notify.finance_id;
            tempVC.isNotify = YES;
            tempVC.view.backgroundColor = WDBackColor;
            [self.navigationController pushViewController:tempVC animated:YES];
            
        }
            break;
            
        case WDPushTypeSalary://工资
        {
            
        }
            break;
            
        case WDPushTypeBusinessDetail://商户详情
        {
            WDBusinessDetailController *tempV = [[WDBusinessDetailController alloc] init];
            
            tempV.view.backgroundColor = WDBackColor;
            
            [self.navigationController pushViewController:tempV animated:YES];
        }
            break;
            
        case WDPushTypeProductDymic://产品更新动态
        {
            
            WDProductDynamicController *tempV = [[WDProductDynamicController alloc] init];
            
            tempV.productID = notify.product_id;
            tempV.productName = notify.product_name;
            tempV.parentLogo = notify.parent_logo;
            tempV.product_status = notify.product_status;
            tempV.isNotify = YES;
            
            tempV.view.backgroundColor = WDBackColor;
            
            [self.navigationController pushViewController:tempV animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}

@end
